$(function() {
	$('[data-toggle="tooltip"]').tooltip();

	var appTagPanel = $('#appTagPanel'),
		appTagListDiv = appTagPanel.find('.list-group'),

		appVersionPanel = $('#appVersionPanel'),
		appTagActionBtns = appVersionPanel.find('.dropdown button');
		appVersionListDiv = appVersionPanel.find('.panel-body:first'),
		appVersionAddDiv = appVersionListDiv.find('.thumbnail').parent();

	var dataStorage = {
		appTagDivs: {
			current: {
				usage: 'fore',
				div: undefined
			},
			fore: [],
			back: []
		},
		appVersionDivs: {
			keys: [],
			keyAndVal: {}
		}
	}

	var appTagUsage = ['fore', 'back'],
		appVersionStatus = [
		    ['info', '未发布'],
		    ['success', '已发布']
		];

	appTagListDiv.height($(window).height() - 200);
	$(window).resize(function() {
	    appTagListDiv.height(Math.max($(this).height() - 200, 330));
	});
	appVersionListDiv.height($(window).height() - 230);
	$(window).resize(function() {
	    appVersionListDiv.height(Math.max($(this).height() - 230, 300));
	});

	function disableAppVersionPanel(disabled) {
		appTagActionBtns.prop('disabled', disabled);
		if (disabled) {
			appVersionAddDiv.addClass('appVersionAddDiv-disabled');
		} else {
			appVersionAddDiv.removeClass('appVersionAddDiv-disabled');
		}
	}

	disableAppVersionPanel(true);

	// Get app tag list
	$.get(URLS.APP_TAG_LIST).done(function(list) {
		console.log(list);
		$.each(list, function(i, appTag) {
			var appTagDiv = constructAppTagDiv(appTag);
			if (appTag.usage == appTagUsage.indexOf('fore')) {
				appTagListDiv.append(appTagDiv);
				dataStorage.appTagDivs.fore.push(appTagDiv);
			} else if (appTag.usage == appTagUsage.indexOf('back')) {
				dataStorage.appTagDivs.back.push(appTagDiv);
			}
		});
		console.log(dataStorage.appTagDivs['fore'])
	});

	// Switch app usage
	appTagPanel.find('.input-group-btn:first button').on('click', function() {
		var $this = $(this);
		$this.removeClass('btn-default').addClass('btn-primary')
			 .siblings().removeClass('btn-primary').addClass('btn-default');
		dataStorage.appTagDivs.current.usage = $this.data('usage');
		appTagListDiv.find('a').detach();
		$.each(dataStorage.appTagDivs[dataStorage.appTagDivs.current.usage], function(i, appTagDiv) {
			appTagListDiv.append(appTagDiv);
		});
	});

	appTagPanel.find('input').on('keyup', function() {
		var $this = $(this);
		appTagListDiv.find('a').detach();
		$.each(dataStorage.appTagDivs[dataStorage.appTagDivs.current.usage], function(i, appTagDiv) {
			if (appTagDiv.text().toLowerCase().indexOf($this.val().toLowerCase()) != -1) {
				appTagListDiv.append(appTagDiv);
			}
		});
	});

	// Add app tag
	appTagPanel.find('.input-group-btn:last button').on('click', function() {
		var appTagAddModal = $.dfaceModal({
			title: '添加应用',
			content: constructAppTagForm({}),
			isForm: true,
			btns: ['取消', '确定']
		}).show();
		appTagAddModal.find('#btnOk').on('click', function() {
			$.post(URLS.APP_TAG_ACTION_ADD, {
				name: appTagAddModal.find('input').val(),
				description: appTagAddModal.find('textarea').val(),
				usage: appTagUsage.indexOf(dataStorage.appTagDivs.current.usage)
			}).done(function(result) {
				if (result.succeeded) {
					var appTagDiv = constructAppTagDiv(result.obj);
					dataStorage.appTagDivs[dataStorage.appTagDivs.current.usage].unshift(appTagDiv);
					appTagListDiv.prepend(appTagDiv);
					appTagAddModal.modal('hide');
				} else {
					constructModalErrorAlert(appTagAddModal, result.message);
				}
			});
		});
	});

	// Edit app tag
	appVersionPanel.find('.dropdown-menu a:first').on('click', function(e) {
		e.preventDefault();
		var selectedAppTagDiv = dataStorage.appTagDivs.current.div;
		var appTagEditModal = $.dfaceModal({
			title: '编辑应用',
			content: constructAppTagForm({
				name: selectedAppTagDiv.text(),
				description: selectedAppTagDiv.attr('data-original-title')
			}),
			isForm: true,
			btns: ['取消', '确定']
		}).show();
		appTagEditModal.find('#btnOk').on('click', function() {
			$.post(URLS.APP_TAG_BY_ID(selectedAppTagDiv.data('sid')), {
 				name: appTagEditModal.find('input').val(),
 				description: appTagEditModal.find('textarea').val()
			}).done(function(result) {
			 	if (result.succeeded) {
			 		selectedAppTagDiv.text(result.obj.name);
			 		selectedAppTagDiv.attr('data-original-title', result.obj.description);
			 		appTagEditModal.modal('hide');
			 	} else {
			 		constructModalErrorAlert(appTagEditModal, result.message);
			 	}
			 });
		});
	});

	// Delte app tag
	appVersionPanel.find('.dropdown-menu a:last').on('click', function(e) {
		e.preventDefault();
		var selectedAppTagDiv = dataStorage.appTagDivs.current.div;
		var appTagDelModal = $.dfaceModal({
			title: '删除应用',
			content: '删除应用, 将删除其所有版本以及API',
			btns: ['取消', '确定']
		}).show();
		appTagDelModal.find('#btnOk').on('click', function() {
			$.ajax({
				url: URLS.APP_TAG_BY_ID(selectedAppTagDiv.data('sid')),
				type: 'DELETE',
			}).done(function(result) {
				if (result.succeeded) {
					var currentUsageDivs = dataStorage.appTagDivs[dataStorage.appTagDivs.current.usage],
						currentSid = selectedAppTagDiv.data('sid');
					for (var i = 0; i < currentUsageDivs.length; i++) {
						if (currentUsageDivs[i].data('sid') == currentSid) {
							currentUsageDivs.splice(i, 1);
							break;
						}
					}
					selectedAppTagDiv.remove();
					dataStorage.appVersionDivs.keys.splice(dataStorage.appVersionDivs.keys.indexOf(currentSid), 1);
					delete dataStorage.appVersionDivs.keyAndVal[currentSid];
					appVersionPanel.find('h3').text('');
					appVersionAddDiv.siblings().remove();
					disableAppVersionPanel(true);
					appTagDelModal.modal('hide');
				} else {
					constructModalErrorAlert(appTagDelModal, result.message);
				}
			});
		});
	});

	function constructAppTagForm(appTag) {
		return '<form action="">' +
					'<div class="form-group">' +
						'<label>应用名称</label>' +
						'<input type="text" class="form-control" value="' + (appTag.name || '') + '">' +
					'</div>' +
					'<div class="form-group">' +
						'<label>应用描述</label>' +
						'<textarea class="form-control" rows="4">' + (appTag.description || '') + '</textarea>' +
					'</div>' +
				'</form>';
	}

	function constructAppTagDiv(appTag) {
		var div = $('<a class="list-group-item" data-sid="' + appTag.sid + '" style=" cursor: pointer;" ' +
					'data-toggle="tooltip" data-placement="right" title="' + appTag.description + '">' + 
					'<span class="glyphicon glyphicon-menu-right pull-right"></span>' + appTag.name + '</a>');
		div.tooltip();
		div.on('click', function(e) {
			e.preventDefault();
			$.each(dataStorage.appTagDivs.fore, function(i, appTagDiv) {
				appTagDiv.removeClass('active');
			});
			$.each(dataStorage.appTagDivs.back, function(i, appTagDiv) {
				appTagDiv.removeClass('active');
			});
			div.addClass('active');

			dataStorage.appTagDivs.current.div = div;

			disableAppVersionPanel(false);

			appVersionPanel.find('h3').text(div.text());

			appVersionAddDiv.siblings().detach();
			var sid = div.data('sid');
			if (dataStorage.appVersionDivs.keys.indexOf(sid) != -1) {
				$.each(dataStorage.appVersionDivs.keyAndVal[sid], function(i, appVersionDiv) {
					appVersionAddDiv.before(appVersionDiv);
				})
			} else {
				$.get(URLS.APP_TAG_BY_ID_VERSION_LIST(sid)).done(function(list) {
					dataStorage.appVersionDivs.keys.push(sid);
					var appVersionDivs = [];
					$.each(list, function(i, appVersion) {
						var appVersionDiv = constructAppVersionDiv(appVersion);
						appVersionDivs.push(appVersionDiv);
						appVersionAddDiv.before(appVersionDiv);
					});
					dataStorage.appVersionDivs.keyAndVal[sid] = appVersionDivs;
				});
			}
			console.log(dataStorage);
		});
		return div;
	}

	// Add app version
	appVersionAddDiv.find('a').on('click', function(e) {
		e.preventDefault();
		var appVersionAddModal = $.dfaceModal({
			title: '添加版本',
			content: constructAppVersionForm({}),
			isForm: true,
			btns: ['取消', '确定']
		}).show();
		appVersionAddModal.find('#btnOk').on('click', function() {
			$.post(URLS.APP_TAG_BY_ID_VERSION_ACTION_ADD(dataStorage.appTagDivs.current.div.data('sid')), {
				version: appVersionAddModal.find('input:first').val(),
				description: appVersionAddModal.find('textarea').val(),
				deployUrl: appVersionAddModal.find('input:last').val(),
				status: 0
			}).done(function(result) {
				if (result.succeeded) {
					var appVersionDiv = constructAppVersionDiv(result.obj);
					dataStorage.appVersionDivs.keyAndVal[dataStorage.appTagDivs.current.div.data('sid')].push(appVersionDiv);
					appVersionAddDiv.before(appVersionDiv);
					appVersionAddModal.modal('hide');
				} else {	
					constructModalErrorAlert(appVersionAddModal, result.message);
				}
			});
		});
	});

	function constructAppVersionForm(appVersion) {
		return '<form action="">' +
					'<div class="form-group">' +
						'<label>Version</label>' +
						'<input type="text" class="form-control" value="' + (appVersion.version || '') + '">' +
					'</div>' +
					'<div class="form-group">' +
						'<label>Description</label>' +
						'<textarea class="form-control" rows="4">' + (appVersion.description || '') + '</textarea>' +
					'</div>' +
					'<div class="form-group">' +
						'<label>Deploy url</label>' +
						'<input type="text" class="form-control" value="' + (appVersion.deployUrl || '') + '">' +
					'</div>' +
				'</form>';
	}

	function constructAppVersionDiv(appVersion) {
		var div = $('<div class="col-lg-4 col-md-6" data-sid="' + appVersion.sid + '">' +
						'<div class="panel panel-default">' +
							'<div class="panel-heading">' +
								'<span class="label label-default" style="margin-right: 5px;">版本号: ' + appVersion.version + '</span>' +
								'<span class="label label-' + appVersionStatus[appVersion.status][0] + '">' + appVersionStatus[appVersion.status][1] + '</span>' +
								'<div class="pull-right">' +
									'<a class="glyphicon glyphicon-edit" style="cursor: pointer; font-size: 1.2em; text-decoration: none; margin-right: 5px;"></a>' +
									'<a class="glyphicon glyphicon-trash" style="cursor: pointer; font-size: 1.2em; text-decoration: none; color: #A94442;"></a>' +
								'</div>' +
							'</div>' +
							'<div class="panel-body" style="height: 100px; overflow: auto;">' + appVersion.description + '</div>' +
							'<div class="panel-footer">' +
								'<div class="input-group">' +
									'<input type="text" class="form-control" readonly value="' + appVersion.deployUrl + '">' +
									'<span class="input-group-btn">' +
										'<button class="btn btn-primary">发布</button>' +
									'</span>' +
								'</div>' +
							'</div>' +
						'</div>' +
					'</div>');
		
		bindEditEventForAppVersion(div);
		bindDelEventForAppVersion(div);
		bindDeployEventForAppVersion(div);
		return div;
	}

	// Edit app version
	function bindEditEventForAppVersion(appVersionDiv) {
		appVersionDiv.find('a:first').on('click', function(e) {
			e.preventDefault();
			var appVersionEditModal = $.dfaceModal({
				title: '编辑版本',
				content: constructAppVersionForm({
					version: appVersionDiv.find('.panel-heading span:first').text().substring(5),
					description: appVersionDiv.find('.panel-body').text(),
					deployUrl: appVersionDiv.find('input').val()
				}),
				isForm: true,
				btns: ['取消', '确定']
			}).show();
			appVersionEditModal.find('#btnOk').on('click', function() {
				$.post(URLS.APP_VERSION_BY_ID(appVersionDiv.data('sid')), {
					version: appVersionEditModal.find('input:first').val(),
					description: appVersionEditModal.find('textarea').val(),
					deployUrl: appVersionEditModal.find('input:last').val(),
				}).done(function(result) {
					if (result.succeeded) {
						appVersionDiv.find('.panel-heading span:first').text('版本号: ' + result.obj.version);
						appVersionDiv.find('.panel-body').text(result.obj.description);
						appVersionDiv.find('input').val(result.obj.deployUrl);
						appVersionEditModal.modal('hide');
					} else {
						constructModalErrorAlert(appVersionEditModal, result.message);
					}
				});
			});
		});
	}

	// Delete app version
	function bindDelEventForAppVersion(appVersionDiv) {
		appVersionDiv.find('a:last').on('click', function(e) {
			e.preventDefault();
			var appVersionDelModal = $.dfaceModal({
				title: '删除版本',
				content: '删除版本, 将删除其所有API',
				btns: ['取消', '确定']
			}).show();
			var sid = appVersionDiv.data('sid');
			appVersionDelModal.find('#btnOk').on('click', function() {
				$.ajax({
					url: URLS.APP_VERSION_BY_ID(sid),
					type: 'DELETE'
				}).done(function(result) {
					if (result.succeeded) {
						var currentAppVersionDivs = dataStorage.appVersionDivs.keyAndVal[dataStorage.appTagDivs.current.div.data('sid')];
						for (var i = 0; i < currentAppVersionDivs.length; i++) {
							if (currentAppVersionDivs[i].data('sid') == sid) {
								currentAppVersionDivs.splice(i, 1);
								break;
							}
						}
						appVersionDiv.remove();
						appVersionDelModal.modal('hide');
					} else {
						constructModalErrorAlert(appVersionDelModal, result.message);
					}
				});
			})
		});
	}

	// Deploy app version
	function bindDeployEventForAppVersion(appVersionDiv) {
		appVersionDiv.find('button').on('click', function() {
			// if (dataStorage.appTagDivs.current.usage == 'fore') {
			// 	deployForForeApp(appVersionDiv);
			// } else if (dataStorage.appTagDivs.current.usage = 'back') {
			// 	deployForBackApp(appVersionDiv);
			// }
			deployApp(appVersionDiv);
		});
	}

	function deployApp(appVersionDiv) {
		var appDeployModal = $.dfaceModal({
	        title: '应用部署',
	        content: '<div class="panel panel-default modal-deploy">' +
			            '<div class="panel-heading"><span class="glyphicon glyphicon-console"></span></div>' +
			            	'<div class="panel-body">' +
			            		'<pre></pre>' +
			            	'</div>' +
		            '</div>',
	        sizeClass: 'big-modal',
	        notDismiss: true,
	        backdrop: 'static',
	        keyboard: false
	    }).show();

		var consoleDiv = appDeployModal.find('pre'),
		    appId = appVersionDiv.data('sid'),
		    isRecordEnd = false;

	    appDeployModal.on('shown.bs.modal', function() {
	        $.get(URLS.APP_VERSION_BY_ID_ACTION_DEPLOY(appId), function(result) {
	            if (result.succeeded) {
	                getRecordById(appId);
	            } else {
	                isRecordEnd = true;
	                constructModalErrorAlert(appDeployModal, result.message);
	            }
	        });
	    });

	    appDeployModal.find('button').on('click', function() {
	        if (isRecordEnd) {
	            appDeployModal.modal('hide');
	        } else {
	            var promptModal = $.dfaceModal({
	                title: '提示',
	                content: '部署脚本正在执行中, 不可退出',
	                sizeClass: 'modal-sm',
	                btns: ['确定']
	            }).show();
	        }
	    });

	    function getRecordById(id) {
	        $.get(URLS.APP_VERSION_BY_ID_ACTION_LOG(id))
	            .done(function(result) {
	                if (result.succeeded) {
	                    var wait;
	                    if (result.deployRecord.message) {
	                        wait = false;
	                        consoleDiv.append(result.deployRecord.message);
	                    } else {
	                        wait = true;
	                    }
	                    if (!result.deployRecord.finished) {
	                        if (wait) {
	                            setTimeout(function() {
	                                getRecordById(id);
	                            }, 5000);
	                        } else {
	                            getRecordById(id);
	                        }
	                    } else {
	                        isRecordEnd = true;
	                        appVersionDiv.find('.panel-heading span:last')
	                            .removeClass('label-info')
	                            .addClass('label-success')
	                            .text('已发布');
	                    }
	                } else {
	                    isRecordEnd = true;
	                    constructModalErrorAlert(appDeployModal, result.message);
	                }
	            });
	    }
	}

	// function deployForForeApp(appVersionDiv) {
	// 	var appDeployModal = $.dfaceModal({
	// 		title: '应用部署',
	// 		content: '正在发布...',
	// 		sizeClass: '<div class="panel panel-default modal-deploy">' +
	// 			            '<div class="panel-heading"><span class="glyphicon glyphicon-console"></span></div>' +
	// 			            	'<div class="panel-body">' +
	// 			            		'<pre></pre>' +
	// 			            	'</div>' +
	// 		            '</div>',
	// 		sizeClass: 'big-modal',
 //            notDismiss: true,
 //            backdrop: 'static',
 //            keyboard: false
	// 	}).show();
	// 	appDeployModal.find('.close').remove();
	// 	appDeployModal.find('#btnOk').prop('disabled', true);
	// 	var isEnd = false;
	// 	$.get(URLS.APP_VERSION_BY_ID_ACTION_DEPLOY(appVersionDiv.data('sid')))
	// 		.done(function(result) {
	// 			appDeployModal.find('#btnOk').prop('disabled', false);
	// 			if (result.succeeded) {
	// 				appDeployModal.modal('hide');
	// 				appVersionDiv.find('.panel-heading span:last')
	//                             .removeClass('label-info')
	//                             .addClass('label-success')
	//                             .text('已发布');
	// 			} else {
	// 				appDeployModal.find('.modal-body').text('发布失败!');
	// 				constructModalErrorAlert(appDeployModal, result.message);
	// 			}
	// 		});
	// }

	function constructModalErrorAlert(modal, msg) {
		modal.find('.modal-body').prepend($.dfaceAlert('danger', '<strong>Error: </strong>' + (msg || 'Excute failed')));
	}

});